﻿using System.Collections.Generic;
using Model;
using NHibernate;
using IDAL;

namespace SqlDALLibrary
{
    public class CommentDal:ICommentDAL
    {
        //保存评论
        public void saveComment(Comment comment)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Save(comment);
                tx.Commit();
            }
            session.Close();
        }

        //删除评论
        public void deleteComment(Comment comment)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Delete(comment);
                tx.Commit();
            }
            session.Close();
        }

        //有问题
        //查看该资源所有评论
        public IList<Comment> getResourceComment(Resource resource)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<Comment> commentList = session.
                CreateQuery("from Comment c where c.resource =: resource")
                .SetParameter("resource", resource)
                .List<Comment>();
            session.Close();
            return commentList;
        }

        //有问题
        //查看用户的所有评论
        public IList<Comment> getUserComment(User user)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<Comment> commentList = session.
                CreateQuery("from Comment c where c.user =: user")
                .SetParameter("user", user)
                .List<Comment>();
            session.Close();
            return commentList;
        }

        //使用ID得到评论
        public Comment getCommentById(int id)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            Comment comment = session
                .CreateQuery("from Comment c where c.id = id")
                .SetInt32("id", id)
                .UniqueResult<Comment>();
            session.Close();
            return comment;
        }

    }
}
